<template>
  <view class="animated fadeIn faster page-bg">
    <NoticeBar :notices="notices"/>

    <view class="d-flex d-flex-between p-2 d-flex-middle">
      <view class="searchBox d-flex-item">
        <text class="iconfont icon-icon_sousuo text"></text>
        <input class="pl-5 bg-fff rounded30  font26 " v-model="formData.name" placeholder="搜索打手名称"
               placeholder-class="colorhold"/>
        <text v-if="formData.name" class="text-right iconfont icon-jiufuqianbaoicon08 main-color ml-1"
              @click="dataCancel"></text>
      </view>
      <view class="search-btn  font28 pl-2" @click="onSearch">
        <text class="color598dfc">搜索</text>
      </view>
    </view>

    <view class="mx-2 py-1 bg-fff category d-flex  d-flex-middle d-flex-wrap rounded20">
      <view v-for="(item,inde) in categoryList.slice(0,4)" :key="inde+'c'" style="width: 140rpx"
            @click="clickCategory(item,inde)" class="d-flex-column d-flex-middle my-1">
        <view class="cate rounded20" :class="{'cateActive':categoryIndex == inde}">
          <image :src="item.icon" class="rounded20 cateImg"></image>
        </view>
        <text class="font24 mt-1">{{ item.name }}</text>
      </view>
      <view v-if="categoryList.length>3" style="width: 20%" class="d-flex-column d-flex-middle my-1" @click="openCate">
        <view class="iconfont icon-a-fenleipinlei font80 color598dfc"></view>
        <text class="font24 mt-1 ">更多品类</text>
      </view>
    </view>

    <view class="mx-2 my-2">
      <swiper indicator-dots autoplay :interval="5000" :duration="1000" indicator-active-color="#ffffff"
              indicator-color="#c6c8c5" class="position-relative"
              style="width:100%;height: 200rpx;border-radius:30rpx;overflow: hidden;">
        <block v-for="(item,idx) in banner" :key="idx+'a'">
          <swiper-item>
            <view class="swiper-item">
              <image :src="item.image" mode="aspectFill" lazy-load
                     style="width:100%;height: 200rpx;border-radius: 30rpx;" @click="goUrl(item.url)">
              </image>
            </view>
          </swiper-item>
        </block>
      </swiper>
    </view>

    <view class="mx-2 my-2">
      <view class="d-flex d-flex-between bg-fff mb-2 rounded20 px-2 py-1 d-flex-middle">
        <text class="font32">推荐大神</text>
        <picker mode="selector" range-key="text" :value="formData.gender" :range="genderOptions" @change="genderChange"
                class="px-2 py-1">
          <view class="d-flex d-flex-middle">
            <text class="iconfont" v-if="formData.gender== 1||formData.gender== 2"
                  :class="formData.gender == 1 ? ' icon-nansheng color598dfc' : 'iconfont icon-nvsheng colorff7bae'"></text>
            <text class="ml-1">{{ genderText }}</text>
            <text class="iconfont icon-xiajiantou color999 ml-1"></text>
          </view>
        </picker>

      </view>
      <view class="mb-5">
        <view v-for="(item,inde) in oneList" :key="inde+'c'"
              class="py-2 px-1 bg-fff rounded20 mb-2 d-flex  d-flex-between ">
          <view class="videoBtnView px-0-5 position-relative" style="width: 30%;">
            <view v-if="item.type == 2" class="d-flex d-flex-column triangle-tag d-flex-middle" >
              <image class="star-image"  @click="goStar('star')"
                     src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/dc522773c8980e119be84d5438a8e11d.png"></image>
<!--              <text class="font20 font-400 purple-blue-gradient triangle-text">明星选手</text>-->
            </view>
            <image :src="item.avatar" class="avatar"
                   @click="goUrl(`/subPages/homePage/homePage?data=${encodeURIComponent(JSON.stringify(item))}`)"></image>
            <view v-if="item.voice_introduce"
                  class="voice-btn d-flex d-flex-middle d-flex-center px-3 py-1 rounded20 font22 "
                  @click="placeOrder(item,inde)">
              <text class="saying mr-1 font28 colorfff"
                    :class="videoIndex == inde?'iconfont icon-saying':'iconfont icon-Gc_10_face-PlayCircle'"></text>
            </view>
          </view>

          <view class="d-flex d-flex-item d-flex-column d-flex-between "
               >
            <view class="font-bold font30  d-flex  d-flex-between d-flex-middle"  >
              <view class="d-flex d-flex-middle" @click="goUrl(`/subPages/orderAlone/orderAlone?data=${encodeURIComponent(JSON.stringify(item))}`)">
                <text :title="item.name" class="text-clamp" style="width: 200rpx">{{ item.name }}</text>
                <text class="px-1 iconfont color598dfc"
                      :class="item.gender == 1 ?'icon-nansheng':'icon-nvshengicon-nvsheng'"></text>
                <text :title="item.unions_name" class="colorff7f02 font26 font-400 text-clamp" style="width: 180rpx">{{ item.unions_name }}</text>
             </view>

            </view>
            <view  @click="goUrl(`/subPages/orderAlone/orderAlone?data=${encodeURIComponent(JSON.stringify(item))}`)" style="height: 66rpx" class=" text-clamp-two font26 mb-1 color333">{{ item.remark }}
            </view>
            <view   class="d-flex d-flex-middle d-flex-between">
              <view class="d-flex d-flex-column font26" @click="goUrl(`/subPages/orderAlone/orderAlone?data=${encodeURIComponent(JSON.stringify(item))}`)">
                <view>
                  <text class="colorf00 font36 font-bold ml-1-5">{{ item.skill_price }}</text>
                  <text class="color999 font22 "> 元/小时</text>
                </view>
              </view>

              <view class="d-flex d-flex-middle" >
                <view v-if="item.star_type==1" @click="goStar(item)">
                  <image  class="imgA px-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/14.png.png"></image>
                </view>
                <view v-if="item.star_type==2" @click="goStar(item)">
                  <image  class="imgA px-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/13.png.png"></image>
                </view>
                <view v-if="item.star_type==3" @click="goStar(item)">
                  <image  class="imgA px-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/12.png.png"></image>
                </view>

                <view  class="ml-1 bgcolor598dfc px-3 py-1 rounded30 colorfff font22" @click="goUrl(`/subPages/orderAlone/orderAlone?data=${encodeURIComponent(JSON.stringify(item))}`)">
                  下单
                </view>
              </view>
            </view>

          </view>
        </view>
      </view>
    </view>

    <view class="load-more d-flex d-flex-center d-flex-column d-flex-middle">
      <image class="mb-2" v-if="loadingType == 2 && oneList.length == 0"
             src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png"
             style="width: 198rpx;height: 128rpx;margin-top: 260rpx;"></image>
      <text>{{ loadingType === 0 ? '上拉显示更多' : (loadingType === 1 ? '正在加载...' : '~ 没有更多数据了 ~') }}</text>
    </view>


    <uni-popup ref="catePopup" :safe-area="false"  type="bottom" style="position: relative;z-index: 999991;">
      <view class="wrap">
        <view class="py-3 d-flex d-flex-between d-flex-middle mb-3">
          <view style="width: 150rpx;"></view>
          <text class="font30 color000">游戏分类</text>
          <view class="d-flex d-flex-middle d-flex-end pr-3" style="width: 120rpx;">
            <text class="iconfont icon-cuo font30 color999" @click="closeCate"></text>
          </view>
        </view>
        <view class="pb-2 px-1">
          <scroll-view style="height: 500rpx;" scroll-y="true" enableBackToTop="true" :scroll-top="0"
                       scroll-with-animation>
            <view class="row">
              <view class="span-4 d-flex d-flex-column d-flex-middle d-flex-center mb-3"
                    v-for="(cate,index) in allCategory" :key="cate.id" :class="{'cate-on':cateIndex==index}"
                    @click="setCate(index,cate.id)">
                <image :src="cate.icon" class="mb-1 cate-img"></image>
                <text class="font24">{{ cate.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  mapState
} from "vuex"
import NoticeBar from '@/components/notice-bar/index.vue'
import {
  homeApi
} from "@/http/homeApi";

export default {
  components: {
    NoticeBar
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
    })
  },
  data() {
    return {
      notices: [],
      banner: [],
      search: '',
      categoryList: [],
      categoryIndex: -1,
      oneList: [],
      refreshing: false,
      loadingMore: false,
      noMoreData: false,
      genderOptions: [
        {text: '性别', value: 0},
        {text: '男', value: 1},
        {text: '女', value: 2}
      ],
      genderText: '性別',
      formData: {
        gender: '',
        name: '',
        game_id: ''
      },
      allCategory: [],
      cateIndex: -1,
      videoIndex: -1,
      // 添加音频上下文引用
      currentAudioContext: null,
      page: 1,
      loadingType:1
    }
  },
  onLoad() {
    this.SwiperBanner();
    this.categories();
    this.play()
  },
  onReachBottom() {
    if (this.loadingType == 2 || this.loadingType == 1) {
      return;
    }
    this.page++
    this.play();
  },
  methods: {
    async SwiperBanner() {
      let res = await homeApi.getBanner('3')
      let res1 = await homeApi.getBanner('4')
      this.notices = res1
      if (res.length > 0) {
        this.banner = res
      } else {
        this.banner = [{
          id: 1,
          image: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/banner.png'
        }]
      }
    },
    async categories() {
      let res = await homeApi.getMyGame()
      this.categoryList = res
    },
    async play() {
      let that = this
      that.loadingType = 1
      console.log(this.page,'page')
      try {
        let params = {
          ...this.formData,
          page: this.page,
        }
        let result = await homeApi.getPlay(params)
        if (result.data) {
          that.oneList = that.oneList.concat(result.data)
        }
        if (result.data && result.data.length > 9) {
          that.loadingType = 0
        } else {
          that.loadingType = 2
        }
      } catch (error) {
        that.loadingType = 2
      }
    },
    clickCategory(item, index) {
      this.categoryIndex = index
      this.cateIndex = -1
      this.oneList = [];
      this.page = 1;
      this.formData.game_id = item.id;
      this.play()
    },
    goUrl(urlPages) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    async onRefresh() {
      this.refreshing = true;
      try {
        // 重新获取数据
        await this.play();
      } finally {
        this.refreshing = false;
      }
    },
    genderChange(e) {
      this.formData.gender = e.detail.value;
      ;
      this.genderText = this.genderOptions[this.formData.gender].text;
      setTimeout(() => {
        this.play();
      }, 1000)
    },
    onSearch() {
      this.play();
    },
    dataCancel() {
      this.formData.name = '';
      setTimeout(() => {
        this.play();
      }, 1000)
    },
    openCate() {
      if (this.allCategory.length == 0) {
        this.getAllCate()
      }
      this.$refs.catePopup.open()
    },
    closeCate() {
      this.$refs.catePopup.close()
    },
    getAllCate() {
      let that = this
      uni.showLoading({
        title: '加载中...'
      })
      homeApi.getAllCategory().then((res) => {
        uni.hideLoading()
        that.allCategory = res
      }).catch((err) => {
        uni.hideLoading()
        console.log('err', err)
      })
    },
    setCate(index, id) {
      let that = this
      that.categoryIndex = -1
      that.cateIndex = index
      that.page = 1;
      that.$refs.catePopup.close()
      this.oneList = [];
      this.page = 1;
      this.formData.game_id = id
      this.play()
    },
    placeOrder(data, index) {
      // 如果点击的是同一个正在播放的项目，则停止播放
      if (this.videoIndex === index) {
        this.stopVoiceIntroduction();
        return;
      }

      this.videoIndex = index;

      // 播放语音介绍
      this.playVoiceIntroduction(data.voice_introduce);
    },

    // 播放语音介绍
    playVoiceIntroduction(voiceUrl) {
      if (!voiceUrl) {
        uni.showToast({
          title: '暂无语音介绍',
          icon: 'none'
        });
        this.videoIndex = -1;
        return;
      }

      // 如果有正在播放的音频，先停止
      if (this.currentAudioContext) {
        this.currentAudioContext.destroy();
      }

      // 创建音频上下文
      this.currentAudioContext = uni.createInnerAudioContext();

      // 设置音频地址
      this.currentAudioContext.src = voiceUrl;

      // 监听播放事件
      this.currentAudioContext.onPlay(() => {
        console.log('开始播放语音介绍');
      });

      // 监听播放结束事件
      this.currentAudioContext.onEnded(() => {
        console.log('语音介绍播放结束');
        this.resetVoiceState();
      });

      // 监听播放错误事件
      this.currentAudioContext.onError((res) => {
        console.error('语音播放失败', res);
        uni.showToast({
          title: '语音播放失败',
          icon: 'none'
        });
        this.resetVoiceState();
      });

      // 开始播放
      this.currentAudioContext.play();
    },

    // 停止播放语音介绍
    stopVoiceIntroduction() {
      if (this.currentAudioContext) {
        this.currentAudioContext.stop();
        this.currentAudioContext.destroy();
        this.currentAudioContext = null;
      }
      this.resetVoiceState();
    },

    // 重置语音播放状态
    resetVoiceState() {
      this.videoIndex = -1;
    },
    goStar(e) {
      if (e.star_type ==1) {
        uni.showToast({
          title: '考核A级',
          icon: 'none',
          duration: 3000,
        });
      }else if (e.star_type == 2) {
        uni.showToast({
          title: '考核s级',
          icon: 'none',
          duration: 3000,
        });
      } else if (e.star_type == 3) {
        uni.showToast({
          title: '考核大神级',
          icon: 'none',
          duration: 3000,
        });
      } else if (e == 'star') {
        uni.showToast({
          title: '明星选手',
          icon: 'none',
          duration: 3000,
        });
      }
    }
  },
  beforeDestroy() {
    // 页面销毁时停止并清理音频资源
    if (this.currentAudioContext) {
      this.currentAudioContext.stop();
      this.currentAudioContext.destroy();
      this.currentAudioContext = null;
    }
  },

}
</script>


<style scoped>
.font80 {
  font-size: 80rpx;
}

.searchBox {
  position: relative;
}

.searchBox input {
  height: 56rpx;
  line-height: 56rpx;
}

.searchBox .text {
  position: absolute;
  left: 13rpx;
  top: 12rpx;
}

.searchBox .text-right {
  position: absolute;
  right: 13rpx;
  top: 12rpx;
  z-index: 9999;
}

.color598dfc {
  color: #598dfc;
}
.bgcolora {
  background-color: #10337b;
}
.bgcolord {
  background-color: #353124;
}
.bgcolors {
  background-color: #473965;
}

.bgcolor598dfc {
  background-color: #598dfc;
}


.callinfo {
  height: 144rpx;
  padding-right: 30rpx;
  border-bottom: solid 1px #ececec;
}

.flex-1-8 {
  flex: 1.8
}

.category {
  background: rgba(255, 255, 255, .3);
}

.px-0-5 {
  padding-left: 6rpx;
  padding-right: 20rpx;
}

.colorff7f02 {
  color: #ff7f02;
}

.cate {
  width: 84rpx;
  height: 84rpx;
  overflow: hidden;
  border: 8rpx solid transparent;
}

.cateImg {
  width: 84rpx;
  height: 84rpx;
}

.cateActive {
  background: #aec8ff;
}

.colorff7bae {
  color: #ff7bae;
}

.cate-on {
  color: #598dfc;
}

.cate-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 20rpx;
  border: solid 2px #ffffff;
}

.cate-on .cate-img {
  border: solid 2px #598dfc;
}


.videoBtnView {
  position: relative;
}

.videoBtnView .avatar {
  width: 206rpx;
  height: 206rpx;
  background: #f6f6f6;
  overflow: hidden;
}

.voice-btn {
  position: absolute;
  bottom: -10rpx;
  left: 0;
  background: linear-gradient(135deg, #a6c0fe, #f68084);
  border: none;
  color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(74, 105, 189, 0.3);
  transition: all 0.3s ease;
  border-radius: 20rpx;
  padding: 10rpx 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-btn:hover {
  background: linear-gradient(135deg, #a6c0fe, #f68084);
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(74, 105, 189, 0.4);
}

/* 录音中状态 */
.voice-btn-recording {
  background: linear-gradient(135deg, #e55039, #eb2f06);
  animation: pulse 1.5s infinite;
}


@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10rpx rgba(255, 107, 107, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0);
  }
}

.saying {
  font-size: 28rpx;
}

.icon-Gc_10_face-PlayCircle {
  font-size: 28rpx;
}

.icon-saying {
  animation: voiceAnimate 1s infinite;
}

@keyframes voiceAnimate {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

.mr-1 {
  margin-right: 10rpx;
}


.saying {
}

.mr-1 {
  margin-right: 10rpx;
}
.purple-blue-gradient {
  background: linear-gradient(45deg, #934f93, #3c3cff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.imgA{
  width: 60rpx;
  height: 60rpx;
}

.position-relative {
  position: relative;
}

.triangle-tag {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  border-top: 80rpx solid #ffffff; /* 紫色三角形 */
  border-right: 80rpx solid transparent;
  z-index: 1;
}

.star-image {
  position: absolute;
  top: -90rpx;
  left: 6rpx;
  width: 44rpx;
  height: 44rpx;
  z-index: 2;
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
}

.triangle-text {
  position: absolute;
  top: 35rpx;
  left: 8rpx;
  font-size: 16rpx;
  color: white;
  z-index: 2;
  transform: rotate(-45deg);
  white-space: nowrap;
}
</style>